import React from "react";

import {Badge,Card,Row,Alert,Col,List,Divider,Select,message,Spin,Collapse,Breadcrumb } from 'antd';

import { Route, Switch} from 'react-router';

import { Link} from 'react-router-dom';

import brace from 'brace';

import cliTruncate from 'cli-truncate';

import AceEditor from 'react-ace';

import 'brace/mode/java';

import 'brace/mode/xml';

import 'brace/mode/velocity';

import 'brace/mode/html';

import 'brace/mode/javascript';

import 'brace/theme/github';

import MemoryRouter from 'react-router/MemoryRouter';

import PageContent from '../PageContent'

import { ajax ,showResultMessage,isNull,isNotNull, isEmpty,setStoreItem,getStoreItem,removesetStoreItem} from '../common';

import UIIcon from '../uicomponents/UIIcon';

import UIForm from '../uicomponents/UIForm';

import UICardTabs from '../uicomponents/UICardTabs';

import UIToolbar from '../uicomponents/UIToolbar';

import UIFormView from '../uicomponents/UIFormView';

import UIView from '../uicomponents/UIView';

import StartJobModla from '../uicomponents/StartJobModla';

import {UIDataTableView} from '../uicomponents/UIDataComponentView';

const Option = Select.Option;

/**
 * 系统功能模块管理
 */
export default class WorkspaceManageApp extends React.Component {
	render() {
		return (
			<PageContent {...this.props} pageInstance={this} >
				<WorkspaceListPanle />
			</PageContent>
		);
	}
}

/** 
 * 产品应用域选择
*/
class WorkspaceListPanle extends React.Component {

	constructor(props) {
		super(props);
        this.state = {
            workspace: null,
			selectedResource: null
        };
	}
	
	componentDidMount() {
		if (getStoreItem('lastSelectWorkspaceId')) {
			ajax('WORKSPACE/getWorkspaceById', { id: getStoreItem('lastSelectWorkspaceId') }, (data) => {
				this.onSelectWorkspace(data);
			});
		}
	}

	loadWorkspaceData = (workspace) => {
		const workspaceId = workspace.id;
		
        if (isNull(this.workspaceInfoRef) === false) {
            this.workspaceInfoRef.loadWorkspaceData(workspaceId);
		}
		
		if (isNull(this.workspaceScmConfigRef) === false) {
            this.workspaceScmConfigRef.loadWorkspaceData(workspaceId);
		}
		
		if (isNull(this.workspaceResourceListRef) === false) {
            this.workspaceResourceListRef.loadWorkspaceData(workspaceId);
		}
		
		if (isNull(this.workspaceFileListRef) === false) {
            this.workspaceFileListRef.loadWorkspaceData(workspaceId,workspace.workspacePath);
		}
		
		if(isNull(this.workspaceModelListRef) === false){
			this.workspaceModelListRef.loadWorkspaceData(workspaceId);
		}

		if(isNull(this.workspacPagelListRef) === false){
			this.workspacPagelListRef.loadWorkspaceData(workspaceId);
		}

		if(isNull(this.workspacStatisticsRef) === false){
			this.workspacStatisticsRef.loadWorkspaceData(workspaceId);
		}
    }

	onSelectWorkspace = (selectedWorkspace) => {
		this.setState({workspace : selectedWorkspace, selectedResource: null});
		setTimeout(() => {
			this.loadWorkspaceData(selectedWorkspace);
		},500);
	}

	onTabChange = (tabName) => {
		const { workspace } = this.state;
        const workspaceId = workspace.id;
        switch (tabName) {
            case 'basicInfo':
                this.workspaceInfoRef.loadWorkspaceData(workspaceId);
				break;
			case 'scmInfo':
                this.workspaceScmConfigRef.loadWorkspaceData(workspaceId);
				break;
			case 'resourceInfo' : 
				this.workspaceResourceListRef.loadWorkspaceData(workspaceId);
				break;
			case 'fileInfo' : 
				this.workspaceFileListRef.loadWorkspaceData(workspaceId,workspace.workspacePath);
				break;
			case 'modelInfo' : 
				this.workspaceModelListRef.loadWorkspaceData(workspaceId);
				break;
			case 'pageInfo' :
				this.workspacPagelListRef.loadWorkspaceData(workspaceId);
				break;
			case 'statisticsInfo' :
				this.workspacStatisticsRef.loadWorkspaceData(workspaceId);
				break;
		}
	}

	actionHandler = (actionEvent) => {

		return {
			addNewWorkspace : () => {
				this.addNewWorkspaceRef.openModal();
			},
			doSave : () => {
				this.addNewWorkspaceRef.getFormData( (formData) => {
					ajax('WORKSPACE/saveWorkspace',formData,(data) => {
						this.addNewWorkspaceRef.closeModal();
						this.workspaceSelectorRef.loadData();
					} );
				} );
			},
			doDelete : () => {
				const { workspace } = this.state;
				const workspaceId = workspace.id;
				
				ajax('WORKSPACE/deletWorkspace',{workspaceId : workspaceId},(data) => {
					this.workspaceSelectorRef.clearSelect();
					this.setState({workspace : null});
				})
			}
		}
	}

    render() {
		const { workspace, selectedResource } = this.state;

		const pageHistory = this.props.history;

		const tabContentMap = {
			'/WorkspaceBasicInfoPanel': {
                getComponent: (owner, props) => {
                    return <WorkspaceInfoPanel {...props} pageHistory={pageHistory} ref={(inst) => this.workspaceInfoRef = inst}/>;
                }
			},
			'/WorkspaceScmConfigPanel' : {
				getComponent: (owner, props) => {
                    return <WorkspaceScmConfigPanel {...props} pageHistory={pageHistory} ref={(inst) => this.workspaceScmConfigRef = inst}/>;
                }
			},
			'/WorkspaceResourceListPanel' : {
				getComponent: (owner, props) => {
                    return <WorkspaceResourceListPanle {...props} pageHistory={pageHistory} ref={(inst) => this.workspaceResourceListRef = inst}/>;
                }
			},
			'/WorkspaceFileListPanle' : {
				getComponent: (owner, props) => {
                    return <WorkspaceFileListPanle {...props} pageHistory={pageHistory} ref={(inst) => this.workspaceFileListRef = inst}/>;
                }
			},
			'/WorkspaceModelListPanel' : {
				getComponent: (owner, props) => {
                    return <WorkspaceModelListPanel {...props} pageHistory={pageHistory} ref={(inst) => this.workspaceModelListRef = inst}/>;
                }
			},
			'/WorkspacePageListPanel' : {
				getComponent: (owner, props) => {
                    return <WorkspacePageListPanel {...props} pageHistory={pageHistory} ref={(inst) => this.workspacPagelListRef = inst}/>;
                }
			},
			'/WorkspaceStatisticsPanle' : {
				getComponent: (owner, props) => {
                    return <WorkspaceStatisticsPanle {...props} pageHistory={pageHistory} ref={(inst) => this.workspacStatisticsRef = inst}/>;
                }
			}
						
		};

		const cardTitle = {
			title: (workspace != null ? <span><UIIcon icon='archive'/>{workspace.name}</span> : <span><UIIcon icon="question"/>{'请选择工程'}</span>),
			extra: <span><UIToolbar actionGroupId="workspaceListActionGroup" actionHandler={this.actionHandler} state={{'delete' : isNull(workspace)}} /> <Divider type="vertical" />  切换工程 <WorkspaceSelect ref={(inst) => this.workspaceSelectorRef = inst} onSelectWorkspace={this.onSelectWorkspace}></WorkspaceSelect></span>,
		}

		const workspaceTabsProps = {
			tabConfigId: 'workspaceTab',
			activeTabKey : this.props.activeTabKey,
			onTabChange: this.onTabChange,
			tabContentMap: tabContentMap,
			...cardTitle,
		}
		
		return (
			<React.Fragment>
				{
					isNull(workspace) === false ? 
						<UICardTabs {...workspaceTabsProps}/>
						: <Card {...cardTitle}/>
				}
				<UIFormView 
					title="新建工程"
					ref={ (inst) => this.addNewWorkspaceRef = inst }
					formConfigId="workspaceForm" 
					actionGroupId="saveActionGroup"
					actionHandler={this.actionHandler}
					inPop={true}
					destroyOnClose={true}
				/>
			</React.Fragment>
			
		);
    }
}

/**
 * 工作区信息
 */
class WorkspaceInfoPanel extends React.Component {

	loadWorkspaceData = (workspaceId) => {

		ajax('WORKSPACE/getWorkspaceById',{id : workspaceId},(data) => {
			this.workspaceFormRef.setFormData(data);
		})
	}

	actionHandler = (actionEvent) => {

		return {
			doSave: () => {
				this.workspaceFormRef.getFormData((formData) => {

					ajax('WORKSPACE/saveWorkspace', formData, (data) => {
						this.workspaceFormRef.setFormData(data);
						showResultMessage({
							success: true,
							message: 'message.saveSuccess',
						});
					});
				});
			}
		};
	}

	render() {
		const workspaceFormProps = {
			formConfigId: 'workspaceEditForm',
			wrappedComponentRef: (inst) => this.workspaceFormRef = inst,
			actionGroupId: 'saveActionGroup',
			actionHandler: this.actionHandler,
		}

		return (
			<UIForm {...workspaceFormProps} {...this.props}>

			</UIForm>
		);
	}
}

/**
 * 工程版本控制配置
 */
class WorkspaceScmConfigPanel extends React.Component {

	state = {
		workspaceId : 0,
	}

	loadWorkspaceData = (workspaceId) => {
		this.setState({workspaceId : workspaceId});
		ajax('WORKSPACE/getWorkspaceScmConfig',{workspaceId : workspaceId},(data) => {
			this.workspaceScmFormRef.setFormData(data);
		})
	}

	actionHandler = (actionEvent) => {
		const {workspaceId} = this.state;
		return {
			doSave: () => {
				this.workspaceScmFormRef.getFormData((formData) => {

					ajax('WORKSPACE/saveWorkspaceScmConfig', formData, (data) => {
						//this.workspaceScmFormRef.setFormData(data);
						showResultMessage({
							success: true,
							message: 'message.saveSuccess',
						});
					});
				});
			},
			importWorkspace : () => {
				ajax('WORKSPACE/getWorkspaceScmConfig',{workspaceId : workspaceId},(data) => {
					this.importWorkspaceJobRef.start(data);
				});
			},
			updateWorkspace : () => {
				ajax('WORKSPACE/getWorkspaceScmConfig',{workspaceId : workspaceId},(data) => {
					this.updateWorkspaceJobRef.start(data);
				});
			}
		};
	}

	render() {

		const {workspaceId,workspaceScmConfig} = this.state;

		const workspaceScmFormProps = {
			formConfigId: 'svnServerConfigForm',
			wrappedComponentRef: (inst) => this.workspaceScmFormRef = inst,
			actionGroupId: 'workspaceScmConfigActionGroup',
			actionHandler: this.actionHandler,
		}
		
		return (
			<React.Fragment>
				<UIForm {...workspaceScmFormProps} {...this.props}>

				</UIForm>
				<StartJobModla key='importWrokspace'
					title='导入工作区'
					startJobUrl="WORKSPACE/importWorkspaceFromScm"
					startJobParamData={{ workspaceId: workspaceId}}
					checkJobUrl="WORKSPACE/checkImportWorkspaceFromScmProgress"
					checkJobParamData={{'workspaceId': workspaceId }}
					showInfo={false}
					ref={(inst) => this.importWorkspaceJobRef = inst}
					
				/>
				<StartJobModla key='updateWrokspace'
					title='更新工作区'
					startJobUrl="WORKSPACE/updateWorkspaceFromScm"
					startJobParamData={{ workspaceId: workspaceId}}
					checkJobUrl="WORKSPACE/checkUpdateWorkspaceFromScmProgress"
					checkJobParamData={{'workspaceId': workspaceId }}
					showInfo={false}
					ref={(inst) => this.updateWorkspaceJobRef = inst}
				/>
			</React.Fragment>
		);
	}
}

/**
 * 工程资源列表
 */
class WorkspaceResourceListPanle extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			workspaceId : props.workspaceId,
		}
	}

	componentDidMount(){
		this._mounted = true;
	}

	componentWillUnmount(){
		this._mounted = false;
	}

	loadWorkspaceData = (workspaceId) => {
		//console.log(this);
		if(workspaceId === undefined){
			if (this.workspaceResourceListRef !== null && this._mounted === true) {
				setTimeout(() => {
					this.workspaceResourceListRef.loadData({workspaceId : workspaceId});
				});
			}
		}
		else{
			this.setState({workspaceId : workspaceId});
			if (this.workspaceResourceListRef !== null && this._mounted === true) {
				setTimeout(() => {
					this.workspaceResourceListRef.loadData({workspaceId : workspaceId});
				});
			}
		}
	}

	actionHandler = (actionEvent) =>{
		const {workspaceId} = this.state;
		return {
			refresh : () => {
				this.workspaceResourceListRef.loadData({workspaceId : workspaceId});
			},
			setResourcePath : () => {
				this.setState({dalogTitle : '设置工程资源'});
				this.workspaceResourceFormRef.openModal();
			},
			removeWorkspaceResource : () => {
				
				const selectResourceId = isNull(actionEvent.params) ? this.selectWorkspaceResourceIds : [actionEvent.params.id];

				ajax( 'WORKSPACE/removeWorkspaceResources', {workspaceResourceIds : selectResourceId},(data) => {
					this.workspaceResourceListRef.loadData({workspaceId : workspaceId});
				});
			},
			doSave : () => {
				this.workspaceResourceFormRef.getFormData( (formData) => {
					formData.workspaceId = workspaceId;
					ajax( 'WORKSPACE/saveWorkspaceResource', formData,(data) => {
						this.workspaceResourceFormRef.closeModal();
						this.workspaceResourceListRef.loadData({workspaceId : workspaceId});
					});
					
				} );
			},
			moveDownWorkspaceResource : () => {
				const selectResourceId = actionEvent.params.id;
			
				ajax("WORKSPACE/moveDownWorkspaceResource",{workspaceResourceId:selectResourceId},(data) =>{
					this.workspaceResourceListRef.loadData({workspaceId : workspaceId});
				});
			},
			moveUpWorkspaceResource : () => {
				const selectResourceId = actionEvent.params.id;
			
				ajax("WORKSPACE/moveUpWorkspaceResource",{workspaceResourceId:selectResourceId},(data) =>{
					this.workspaceResourceListRef.loadData({workspaceId : workspaceId});
				});
			},
		};
	}

	render(){
		const { currentResource} = this.props;

		const {workspaceId,dalogTitle} = this.state;

		if (workspaceId !== null) {

			const workspaceResourceTableProps = {
				ref: (inst) => { this.workspaceResourceListRef = inst },
				bordered : false,
				actionHandler: this.actionHandler,
				actionGroupId: "workspaceResourceListActionGroup",
				rowActionGroupId : "workspaceResourceRowActionGroup",
				tableConfigId: "workspaceResourceListTable",
				dataUrl: "WORKSPACE/queryWorspaceResouces",
				selectMode: "multi",
				autoLoad: false,
				onSelectChange: (selectRowKeys) => {
					this.selectWorkspaceResourceIds = selectRowKeys;
				},
				setToolbarState: (topToolBar, selectedIds) => {
					if (selectedIds.length > 0) {
						topToolBar.enable('removeWorkspaceResource');
						topToolBar.enable('moveUp');
						topToolBar.enable('moveDown');
						topToolBar.enable('moveModule');
					}
					else {
						topToolBar.disable('removeWorkspaceResource');
						topToolBar.disable('moveUp');
						topToolBar.disable('moveDown');
						topToolBar.disable('moveModule');
					}
				},
				cellRender : (column,CellContent,data,dataSet) => {
					if(column.property === 'status'){
						CellContent.splice(0, 0, <Badge key={data.id} status={data.status === 'IN_USE' ? 'processing' : 'error'} />);
					}
				}
			};

			return (
				<React.Fragment>
					<UIDataTableView {...workspaceResourceTableProps}/>
					<UIFormView 
						params={workspaceId}
						title={dalogTitle}
						inPop={true}
						destroyOnClose={true}
						formConfigId="workspaceResourceForm"
						actionGroupId="saveActionGroup"
						actionHandler={this.actionHandler}
						ref={inst => { this.workspaceResourceFormRef = inst }}
					/>
				</React.Fragment >
			);
		}
		else {
			return <div />
		}
	}
}

/**
 * 工程文件列表
 */
class WorkspaceFileListPanle extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			workspaceId : props.workspaceId,
			loading: false,
			parentPath : '',
			list: [],
		}
	}

	loadWorkspaceData = (workspaceId,parentPath) => {

		this.setState({workspaceId : workspaceId,loading : true,parentPath : parentPath});

		if(isNull(this.fileRouter) === false && this.fileRouter.history.location.pathname === '/fileInfo'){
			this.fileRouter.history.push('/');
		}
				
		ajax('WORKSPACE/getWorspaceFileResouces',{workspaceId : workspaceId,parentResourcePath : parentPath},(data) => {
						
			this.setState({list : data,loading : false});
		});
	}

	loadWorkspaceFolderData = (parentPath) => {
		const { workspaceId } = this.state;
		this.setState({loading : true,parentPath : parentPath});
		
		ajax('WORKSPACE/getWorspaceFileResouces',{workspaceId : workspaceId,parentResourcePath : parentPath},(data) => {
			this.setState({list : data,loading : false});
		});
	}

	loadWorkspaceFileData = (router,filePath) => {
		this.fileRouter = router;
		router.history.push('/fileInfo',filePath);
	}

	renderFilePath = (parentPath) => {

		if(parentPath === undefined){
			parentPath = '/';
		}

		const paths = parentPath.split('/');
		
		const pathStep = paths.map((path,index) => {
			return <Breadcrumb.Item key={index}>{index === 0 ?  <span><UIIcon icon="folder" />文件导航栏 ：</span> : ''}<a onClick={(e) => { this.loadWorkspaceFolderData(paths.slice(0,index + 1).join('/') )}}>{path}</a></Breadcrumb.Item>
		})

		return (
			<span> 
				<Breadcrumb>
				{
					pathStep
				}
				</Breadcrumb>
			</span>
		);
	}

	render(){
		const { loading, list,workspaceId,parentPath } = this.state;
		return (
			<MemoryRouter>
				<Switch>
					<Route exact path="/" component={(router) => {
						return (
							<List
								bordered={true}
								loading={loading}
								itemLayout="horizontal"
								dataSource={list}
								header={this.renderFilePath(parentPath)}
								renderItem={item => (
								<List.Item >
									
									<List.Item.Meta
										title={<a onClick={(e) => { item.directory ?  this.loadWorkspaceFolderData(item.workspaceBean.workspacePath + '/' + item.resourcePath) : this.loadWorkspaceFileData(router,item.workspaceBean.workspacePath + '/' + item.resourcePath)} }><UIIcon icon={item.directory ? 'folder' : 'file'} fixedWidth /> {item.name}</a>}
										description={item.directory === false ? (item.versionInfo !== null ? <span><UIIcon icon="tags" />{item.versionInfo.revision + ' - ' + item.versionInfo.lastCommitAuthor + ' - ' + item.versionInfo.relativeDate}</span> : '') : ''}
									/>
									<div>{item.resourcePath}</div>
									
								</List.Item>
								)}
							/>
							)
						}
					}/>
					<Route exact path="/fileInfo" component={(router) => {
						
						return (
							<UICardTabs 
								title={<span><UIIcon icon="file" /> {cliTruncate(router.location.state + '',100 ,{position: 'middle'})}</span>}
								extra={<Link to="/">返回</Link>}
								tabConfigId="workspaceSourceFileTab"
								tabContentMap = {{
									'/WorkspaceSourceFileBasicInfoPanel': {
										getComponent: (owner, props) => {
											return <WorkspaceSourceFileBasicInfoPanel workspaceId={workspaceId} filePath={router.location.state} {...props} ref={(inst) => this.workspaceFileBasicInfoRef = inst}/>;
										}
									},
									'/WorkspaceSourceFileContentInfoPanel' : {
										getComponent: (owner, props) => {
											return <WorkspaceSourceFileContentInfoPanel  workspaceId={workspaceId} filePath={router.location.state} {...props} ref={(inst) => this.workspaceFileContentRef = inst}/>;
										}
									},
									'/WorkspaceSourceFileVersionInfoPanel' : {
										getComponent: (owner, props) => {
											return <WorkspaceSourceFileVersionInfoPanel  workspaceId={workspaceId} filePath={router.location.state} {...props} ref={(inst) => this.workspaceFileVersionRef = inst}/>;
										}
									},
									
									
								}}
							/>
						);
					}}/>

				</Switch>
			</MemoryRouter>
			
		);
	}
}


/**
 * 文件信息页面
 */
class WorkspaceSourceFileBasicInfoPanel extends React.Component {

	componentDidMount() {
		const { workspaceId,filePath} = this.props;

		if(isNull(this.workspaceFileFormRef) === false){

			ajax('WORKSPACE/getFileBasicInfo',{workspaceId : workspaceId,path : filePath},(data) => {
				this.workspaceFileFormRef.setFormData(data);
			});
		}
	}

	render(){
		const workspaceFileFormProps = {
			formConfigId: 'fileBasicInfoForm',
			wrappedComponentRef: (inst) => this.workspaceFileFormRef = inst,
		}

		return (
			<UIForm {...workspaceFileFormProps} {...this.props}>

			</UIForm>
		);
		
	}
	
}

/**
 * 文件内容页面
 */
class WorkspaceSourceFileContentInfoPanel extends React.Component {

	state = {
		fileContent : '',
		fileType : '',
	}

	componentDidMount() {
		const { workspaceId,filePath} = this.props;

		ajax('WORKSPACE/getFileContentInfo',{workspaceId : workspaceId,path : filePath},(data) => {
			this.setState({fileContent : data.content,fileType : data.fileType});
		});
	}


	render(){

		const {fileContent,fileType} = this.state;

		return (
			<AceEditor 
				mode={fileType} 
				theme="github" 
				width="100%" 
				readOnly={true} 
				value={fileContent} 
				ref={ (inst) => this.fileContentEditor = inst } 
			/>
		);
	}
	
}

class WorkspaceSourceFileVersionInfoPanel extends React.Component {

	state = {
		rightFileContent : '',
		leftFileContent : '',
		leftVersion : '',
		rightVersion : '',
		leftMarkers : [],
		rightMarkers : [],
		fileType : '',
		loadingDif : false,
	}

	componentDidMount() {
		const { workspaceId,filePath} = this.props;

		if(this.fileVersionListRef !== null){
			this.fileVersionListRef.loadData({workspaceId : workspaceId,path : filePath});
		}
	}

	actionHandler = (actionEvent) => {
		const { workspaceId,filePath} = this.props;
		const {selectResourceVersions} = this;
        return {
			refresh : () => {
				this.fileVersionListRef.loadData({workspaceId : workspaceId,path : filePath});
			},
			compareResourceVersion : () => {
				this.setState({loadingDif : true});
				this.showVersionDifRef.openModal(() => {
					ajax('WORKSPACE/compareWorkspaceResource',{workspaceId : workspaceId,path:filePath,leftVersion : selectResourceVersions[0],rightVersion : selectResourceVersions[1]},(data) => {
						console.log(data);
	
						const rightMarkers = [];
	
						const leftMarkers = [];
	
						for(let i = 0 ; i < data.leftDiffDetails.length;i++){
								
							leftMarkers.push({startRow : data.leftDiffDetails[i].lineNumber - 1,startCol : 0,endRow : data.leftDiffDetails[i].lineNumber -1, endCol : 200,className : "ace_stack",type : "fullLine"});
						}
						
						for(let i = 0 ; i < data.rightDiffDetails.length;i++){
							rightMarkers.push({startRow : data.rightDiffDetails[i].lineNumber - 1,startCol : 0,endRow : data.rightDiffDetails[i].lineNumber -1, endCol : 200,className : "ace_stack",type : "fullLine"});
						}
	
						this.setState({
							rightFileContent : data.rightContent,
							leftFileContent : data.leftContent,
							fileType : data.fileType,
							leftVersion : data.leftVersion,
							rightVersion : data.rightVersion,
							rightMarkers : rightMarkers,
							leftMarkers : leftMarkers,
							loadingDif : false,
						});
						
					});
				});
			
			}
		}
	}

	onRightScroll = (scroll ) => {
		//console.log(scroll);
		this.leftFileContent.editor.session.setScrollTop(parseInt(scroll.session.$scrollTop) || 0);
	}

	onLeftScroll = (scroll ) => {
		if(isNotNull(this.rightFileContent)){
			this.rightFileContent.editor.session.setScrollTop(parseInt(scroll.session.$scrollTop) || 0);
		}
	}

	render(){

		const {leftFileContent,rightFileContent,fileType,leftVersion,rightVersion,leftMarkers,rightMarkers} = this.state;

		return (
			<React.Fragment>
				<UIDataTableView 
					tableConfigId="fileResopurceVersionLogTable"
					actionGroupId="fileVersionInfoActionGroup"
					dataUrl="WORKSPACE/queryResourceFileVersionInfo"
					autoLoad={false}
					bordered={false}
					actionHandler={this.actionHandler}
					ref={ (inst) => this.fileVersionListRef = inst }
					setToolbarState={(topToolBar, selectRowKeys) => {
						if (selectRowKeys.length > 1) {
							topToolBar.enable('compareResourceVersion');
						} else {
							topToolBar.disable('compareResourceVersion');
						}
					}}
					onSelectChange={
						(selectRowKeys) => {
							this.selectResourceVersions = selectRowKeys;
						}
					}
				/>
				<UIView title={"版本差异比较" + leftVersion + " - " + rightVersion} width={1200} inPop={true} ref={ (inst) => { this.showVersionDifRef = inst } }>
					<Spin spinning={this.state.loadingDif}>
					<Row gutter={16}>
						<Col span={12}>
						<AceEditor 
							name="leftEditor"
							mode={fileType} 
							theme="github" 
							width="100%" 
							readOnly={true} 
							value={leftFileContent}
							markers={leftMarkers}
							ref={ (inst) => this.leftFileContent = inst } 
							onScroll={this.onLeftScroll}
						/>
						</Col>
						<Col span={12}>
						<AceEditor 
							name="rightEditor"
							mode={fileType} 
							theme="github" 
							width="100%" 
							readOnly={true} 
							value={rightFileContent}
							markers={rightMarkers}
							ref={ (inst) => this.rightFileContent = inst }
							onScroll={this.onRightScroll}
						/>
						</Col>
					</Row>
					</Spin>
				</UIView>
			</React.Fragment>
			
		);
	}
	
}

/** 
 * 工程选择
*/
class WorkspaceSelect extends React.Component {

	constructor(props) {
		super(props);
        this.workspaceList = [];
        this.state = {
            workspaceList : [],
        };
	}


	renderWorkspace = (workspace) => {
		let color = "processing";
		if ('IN_USE' === workspace.status) {
			color = 'processing'
		}
		else if ('CLOSED' === workspace.status) {
			color = 'error'
		}

		return (<Badge status={color} style={{ marginLeft: 6 }} text={<span><UIIcon icon='archive'/>{workspace.name}</span>} />)
	}

	handleSelect = (value, opt) => {
		const { workspaceList } = this.state;
		setStoreItem('lastSelectWorkspaceId', value);
		if (this.props.onSelectWorkspace) {
			workspaceList.map(workspace => {
				if(workspace.id + '' === value){
					this.props.onSelectWorkspace(workspace);
				}
			});
		}
    }
    
    componentDidMount(){
        this.loadData();
	}
	
	loadData = () => {
		ajax('WORKSPACE/getWorkspaceList',{},(data => {
            this.setState({workspaceList : data});
        }));
	}

	clearSelect = () => {
		removesetStoreItem('lastSelectWorkspaceId');
		this.loadData();
	}

	render() {
		const { workspaceList } = this.state;
		return (
			<Select style={{ width: 250 }}
				onSelect={this.handleSelect}
				placeholder="请选择工程"
				defaultValue={getStoreItem('lastSelectWorkspaceId')}
			>
				{workspaceList.map(workspace => (
					<Option key={workspace.id} value={workspace.id + ''}>{this.renderWorkspace(workspace)}</Option>
				))}
			</Select>
		);
	}
}

/**
 * 关联模型列表
 */
class WorkspaceModelListPanel extends React.Component {

	state = {
		workspaceId : 0,
	}

	loadWorkspaceData = (workspaceId) => {
		this.setState({workspaceId : workspaceId});
		this.workspaceModelListRef.loadData({workspaceId : workspaceId});
	}

	actionHandler = (actionEvent) => {
		const {workspaceId} = this.state;
		const {selectWorkspaceModelIds,addModelRelateViewRef,workspaceModelListRef,selectResourceFormRef,selectPackageIds} = this;
		return {
			genSourceCode : () => {
				//console.log(selectWorkspaceModelIds);
				this.genWorkspaceSourceCodeJobRef.start({workspaceId : workspaceId,resourceRelateModelPackageIds:selectWorkspaceModelIds});
			},
			add : () => {
				addModelRelateViewRef.openModal();
			},
			addRelatedItems : () => {
				selectResourceFormRef.getFormData((formData) => {
					ajax('WORKSPACE/addWorkspaceResourceModelPackages',{workspaceResourceId : formData.sourceCodeResource,modelPackageIds : selectPackageIds},(data) => {
						addModelRelateViewRef.closeModal();
						workspaceModelListRef.loadData({workspaceId : workspaceId});
					});
				});
			},
			cancelChoose : () => {
				addModelRelateViewRef.closeModal();
			},
			doRemove : () => {
				ajax('WORKSPACE/removeWorkspaceResourceModelPackages',{ids : selectWorkspaceModelIds},(data) => {
					workspaceModelListRef.loadData({workspaceId : workspaceId});
				});
			},
		};
	}

	onGenCodeFinsihed = () => {
		const {workspaceId} = this.state;
		this.workspaceModelListRef.loadData({workspaceId : workspaceId});
	}

	render(){
		const {workspaceId} = this.state;
		const workspaceModelTableProps = {
			ref: (inst) => { this.workspaceModelListRef = inst },
			bordered : false,
			actionHandler: this.actionHandler,
			actionGroupId: "workspaceResourceBusinessPackageRelateListActionGroup",
			//rowActionGroupId : "workspaceResourceRowActionGroup",
			tableConfigId: "workspaceResourceBusinessPackageRelate",
			dataUrl: "WORKSPACE/queryWorkspaceResourceRelatedBusinessPackages",
			selectMode: "multi",
			autoLoad: false,
			onSelectChange: (selectRowKeys) => {
				this.selectWorkspaceModelIds = selectRowKeys;
			},
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('genSourceCode');
					topToolBar.enable('remove');
				}
				else {
					topToolBar.disable('genSourceCode');
					topToolBar.disable('remove');
				}
			}
		};

		const modelPackageProps = {
            ref: (inst) => { this.packageListRef = inst },
            actionHandler: this.actionHandler,
            actionGroupId: 'chooseResourceRelateModePackageActionGroup',
            tableConfigId: 'modelPackageList',
            dataUrl: 'PRODUCT/MODEL/productModelPackage/queryModelPackages',
			params : {excludePackageType : 'DB'},
            selectMode: 'multi',
            searchFormId: 'resourceRelateModelPackageSearchForm',
            autoLoad: true,
            setToolbarState: (topToolBar, selectedIds) => {
                if (selectedIds.length > 0) {
                    topToolBar.enable('ok');
                }
                else {
                    topToolBar.disable('ok');
                }
            },
            onSelectChange:
                (selectRowKeys) => {
                    this.selectPackageIds = selectRowKeys;
                }
            ,
        };

		return (
			<React.Fragment>
				<UIDataTableView {...workspaceModelTableProps} />
				<StartJobModla key='genSourcecode'
					title='生成代码'
					startJobUrl="WORKSPACE/genWorkspaceSourceCode"
					//startJobParamData={{ workspaceId: workspaceId}}
					checkJobUrl="WORKSPACE/checkGenWorkspaceSourceCode"
					checkJobParamData={{'workspaceId': workspaceId }}
					ref={(inst) => this.genWorkspaceSourceCodeJobRef = inst}
					onJobFinish={this.onGenCodeFinsihed}
				/>
				<UIView 
					title="添加关联模型" 
					inPop={true} ref={ (inst) => { this.addModelRelateViewRef = inst } } 
					actionHandler={this.actionHandler}
					width={1000}
				>
					<UIForm formConfigId="workspaceSourcePathForm" params={workspaceId} wrappedComponentRef={(inst) => { this.selectResourceFormRef = inst }}/>
					<UIDataTableView {...modelPackageProps} />
				</UIView>
			</React.Fragment>
		);
	}
}

/**
 * 关联页面列表
 */
class WorkspacePageListPanel extends React.Component {

	state = {
		workspaceId : 0,
	}

	loadWorkspaceData = (workspaceId) => {
		this.setState({workspaceId : workspaceId});
		this.workspacePageListRef.loadData({workspaceId : workspaceId});
	}

	actionHandler = (actionEvent) => {
		const {workspaceId} = this.state;
		const {selectWorkspacePageIds,selectUIPageIds,addPageRelateViewRef,workspacePageListRef,selectResourceFormRef} = this;
		return {
			genSourceCode : () => {
				this.genWorkspaceSourceCodeJobRef.start({workspaceId : workspaceId,uiPageIds:selectWorkspacePageIds});
			},
			add : () => {
				addPageRelateViewRef.openModal();
			},
			addRelatedItems : () => {
				selectResourceFormRef.getFormData((formData) => {
					ajax('WORKSPACE/ProductUIPageRelate/addWorkspaceResourceUIPages',{workspaceResourceId : formData.webPageResource,uiPageIds : selectUIPageIds},(data) => {
						addPageRelateViewRef.closeModal();
						workspacePageListRef.loadData({workspaceId : workspaceId});
					});
				});
			},
			cancelChoose : () => {
				addPageRelateViewRef.closeModal();
			},
			doRemove : () => {

				const selectIds = isNull(actionEvent.params) ? this.selectWorkspacePageIds : [actionEvent.params.id];
				
				ajax('WORKSPACE/ProductUIPageRelate/batchDelete',{ids : selectIds},(data) => {
					workspacePageListRef.loadData({workspaceId : workspaceId});
				});
			},
			//
		};
	}

	onGenCodeFinsihed = () => {
		const {workspaceId} = this.state;
		this.workspacePageListRef.loadData({workspaceId : workspaceId});
	}

	render(){
		const {workspaceId} = this.state;
		const workspacePageTableProps = {
			ref: (inst) => { this.workspacePageListRef = inst },
			bordered : false,
			actionHandler: this.actionHandler,
			actionGroupId: "webPageRelateListActionGroup",
			//rowActionGroupId : "workspaceResourceRowActionGroup",
			tableConfigId: "workspaceWebPageResourceUIPageRelateTable",
			dataUrl: "WORKSPACE/ProductUIPageRelate/query",
			selectMode: "multi",
			autoLoad: false,
			onSelectChange: (selectRowKeys) => {
				this.selectWorkspacePageIds = selectRowKeys;
			},
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('genSourceCode');
					topToolBar.enable('remove');
				}
				else {
					topToolBar.disable('genSourceCode');
					topToolBar.disable('remove');
				}
			}
		};

		const pageTableProps = {
            ref: (inst) => { this.pageListRef = inst },
            actionHandler: this.actionHandler,
            actionGroupId: 'chooseResourceRelateUIPageActionGroup',
            tableConfigId: 'productUIPageTable',
            dataUrl: 'PRODUCT/UI/ProductUIPage/query',
            selectMode: 'multi',
            searchFormId: 'productUIPageSearchForm',
            autoLoad: true,
            setToolbarState: (topToolBar, selectedIds) => {
                if (selectedIds.length > 0) {
                    topToolBar.enable('ok');
                }
                else {
                    topToolBar.disable('ok');
                }
            },
            onSelectChange:
                (selectRowKeys) => {
                    this.selectUIPageIds = selectRowKeys;
                }
            ,
        };


		return (
			<React.Fragment>
				<UIDataTableView {...workspacePageTableProps} />
				<StartJobModla key='genPageSourcecode'
					title='生成代码'
					startJobUrl="WORKSPACE/ProductUIPageRelate/genWorkspaceResourceSourceCode"
					//startJobParamData={{ workspaceId: workspaceId}}
					checkJobUrl="WORKSPACE/ProductUIPageRelate/checkGenWorkspaceResourceSourceCode"
					checkJobParamData={{'workspaceId': workspaceId }}
					ref={(inst) => this.genWorkspaceSourceCodeJobRef = inst}
					onJobFinish={this.onGenCodeFinsihed}
				/>
				<UIView 
					title="添加关联UI页面" 
					inPop={true} ref={ (inst) => { this.addPageRelateViewRef = inst } } 
					actionHandler={this.actionHandler}
					width={1000}
				>
					<UIForm formConfigId="workspaceWebPagePathForm" params={workspaceId} wrappedComponentRef={(inst) => { this.selectResourceFormRef = inst }}/>
					<UIDataTableView {...pageTableProps} />
				</UIView>
			</React.Fragment>
		);
	}
}

/**
 * 工作空间统计信息
 */
class WorkspaceStatisticsPanle extends React.Component {

	state = {
		workspaceId : 0,
	}

	loadWorkspaceData = (workspaceId) => {
		this.setState({workspaceId : workspaceId});
	}

	actionHandler = (actionEvent) => {
		const {workspaceId} = this.state;
		return {
			genScmReport : () => {
				ajax('WORKSPACE/genWorkspaceSCMReport',{workspaceId : workspaceId},(data) => {
					console.log(data);
				});
			}
		};
	}

	render(){
		return (
			//workspaceDashboardActionGroup
			<UIView 
				title="数据统计" 
				actionGroupId="workspaceDashboardActionGroup"
				actionHandler={this.actionHandler}
			>
			</UIView>
		);
	}
}
